package com.stars.easyms.mq.core;

import com.stars.easyms.mq.core.activemq.ActiveMQMessageSender;
import com.stars.easyms.mq.core.rocketmq.RocketMQMessageSender;
import com.stars.easyms.mq.enums.MQ;
import com.stars.easyms.mq.properties.EasyMsMQProperties;
import org.springframework.context.ApplicationContext;

/**
 * MQ消息发送者工厂类
 *
 * @author guoguifang
 * @date 2018-04-23 13:54
 * @since 1.0.0
 */
public final class MQMessageSenderFactory {

    private ApplicationContext applicationContext;

    private String applicationId;

    private MQMessageSender activeMQMessageSender;

    private MQMessageSender rocketMQMessageSender;

    private EasyMsMQProperties easyMsMQProperties;

    MQMessageSender getMQMessageSender() {
        return easyMsMQProperties.getActive() == MQ.ACTIVEMQ ? getActiveMQMessageSender() : getRocketMQMessageSender();
    }

    private MQMessageSender getActiveMQMessageSender() {
        MQMessageSender localActiveMQMessageSender = activeMQMessageSender;
        if (localActiveMQMessageSender == null) {
            synchronized (MQMessageSenderFactory.class) {
                localActiveMQMessageSender = activeMQMessageSender;
                if (localActiveMQMessageSender == null) {
                    activeMQMessageSender = localActiveMQMessageSender = new ActiveMQMessageSender(applicationContext, easyMsMQProperties);
                }
            }
        }
        return localActiveMQMessageSender;
    }

    private MQMessageSender getRocketMQMessageSender() {
        MQMessageSender localRocketMQMessageSender = rocketMQMessageSender;
        if (localRocketMQMessageSender == null) {
            synchronized (MQMessageSenderFactory.class) {
                localRocketMQMessageSender = rocketMQMessageSender;
                if (localRocketMQMessageSender == null) {
                    rocketMQMessageSender = localRocketMQMessageSender = new RocketMQMessageSender(applicationId, easyMsMQProperties);
                }
            }
        }
        return localRocketMQMessageSender;
    }

    public MQMessageSenderFactory(ApplicationContext applicationContext, String applicationId, EasyMsMQProperties easyMsMQProperties) {
        this.applicationContext = applicationContext;
        this.applicationId = applicationId;
        this.easyMsMQProperties = easyMsMQProperties;
    }

}
